﻿

namespace Mulala.Cavan.Presentation.Mvc.Controller
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Mvc;
    using Mulala.Cavan.Application.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Application.MainBoundedContext.ConsignModule;
    using Mulala.Cavan.Application.MainBoundedContext.CorporationModule;
    using Mulala.Cavan.Application.MainBoundedContext.InformationModule;
    using Mulala.Cavan.Application.MainBoundedContext.NannyModule;
    using Mulala.Cavan.Core.Extension;
    using Mulala.Cavan.Core.Settings;
    using Mulala.Cavan.Domain.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Domain.MainBoundedContext.ConsignModule;
    using Mulala.Cavan.Domain.MainBoundedContext.CorporationModule;
    using Mulala.Cavan.Domain.MainBoundedContext.InformationModule;
    using Mulala.Cavan.Domain.MainBoundedContext.NannyModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SecurityModule;
    using Mulala.Cavan.Domain.MainBoundedContext.Setting;
    using Mulala.Cavan.Domain.Seedwork;
    using Mulala.Cavan.Presentation.Mvc.ViewModel;
    using Mulala.Cavan.Presentation.Seedwork;
    using Mulala.Cavan.Core.Helper;
    using Mulala.Cavan.Application.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Application.Seedwork;

    public class CorporationCenterController : EntityController<Corporation, CorporationSearch, ICorporationViewModel, ICorporationAppService>, ICorporationCenterController
    {
        private IAttachmentAppService AttachmentAppService { get; set; }
        private IConsignAppService ConsignAppService { get; set; }
        private IFileUploadAppService FileUploadAppService { get; set; }
        private INannyAppService NannyAppService { get; set; }
        private ICorporationNewAppService CorporationNewAppService { get; set; }
        private IUserMessageAppService UserMessageAppService { get; set; }
        private INoteAppService NoteAppService { get; set; }

        public override string ControllerName
        {
            get { return ControllerConst.CORPORATIONCENTER; }
        }

        public override bool UseDenied
        {
            get { return true; }
        }

        public CorporationCenterController()
        {
            this.Model = ModelFactory.CreateModel<ICorporationViewModel>();
        }

        [ActionName(ActionConst.INDEX)]
        public ActionResult GetUserCenterInfo()
        {
            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            CorporationViewModelConverter.Convert(corporation, this.Model);
            this.Model.NannyCount = corporation.Nannies != null ? corporation.Nannies.Count : 0;
            this.Model.BiddingConsignCount = corporation.ConsignBidders != null ? corporation.ConsignBidders.Count : 0;
            this.Model.BiddingSuccessConsignCount = corporation.ConsignBidders != null ? corporation.ConsignBidders.Count(cb => cb.ConsignBidderStatus == ConsignIdentifier.ConsignBidderStatus.IsAccepted) : 0;
            NoteReceiverSearch noteReceiverSearch = NoteReceiverSearchFactory.CreateNoteReceiverSearch(this.Model.MasterModel.CurrentUserModel.UserAccountID, true);
            this.SaveCorporationUnReadNote(this.NoteAppService.GetUnReadNoteCount(noteReceiverSearch));
            return View(this.Model);
        }

        [ActionName(ActionConst.PARTINFO)]
        [ChildActionOnly]
        public ActionResult GetCorporationPartInfo()
        {
            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            CorporationViewModelConverter.Convert(corporation, this.Model);

            return PartialView("~/Views/CorporationCenter/_corporationAccessPartial.cshtml", this.Model);
        }

        [HttpGet]
        [ActionName(ActionConst.LOGO)]
        public ActionResult GetCorporationLogo()
        {
            ICorporationLogoViewModel model = ModelFactory.CreateModel<ICorporationLogoViewModel>();
            Corporation corporation = CorporationFactory.CreateCorporation(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            model.Logo = this.AttachmentAppService.GetCorporationLogo(corporation);
            model.AttachmentGroup = AttachmentIdentifier.AttachmentGroup.CorporationLogo;
            if (this.HttpContext.Request["img"] != null)
            {
                model.LogoForEdit = this.HttpContext.Request["img"].ToString();
            }
            else
            {
                model.LogoForEdit = Project.Settings.ImageServer + Project.Settings.DefaultLogoForEditUrl;
            }
            return View(model);
        }

        [HttpPost]
        [ActionName(ActionConst.LOGO)]
        public JsonResult UpdateCorporationLogo(CorporationLogoViewModel corporationLogo)
        {
            string temp = corporationLogo.Logo.Replace(Global.Settings.TempImageServer, "").Replace("%C3%97", "×");
            string fileUrl = temp.Substring(0, temp.LastIndexOf('/') + 1);
            string oldFileName = temp.Substring(fileUrl.LastIndexOf('/') + 1);
            string newFileName = "logo" + oldFileName;
            FileUploadAppService.CutPhoto(AttachmentIdentifier.AttachmentGroup.CorporationLogo.GetHashCode(), fileUrl, oldFileName, newFileName, corporationLogo.Width, corporationLogo.Height, corporationLogo.X, corporationLogo.Y);
            FileUploadAppService.CopyFile(fileUrl, newFileName);

            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            Attachment logo = this.AttachmentAppService.GetCorporationLogo(corporation.ID);
            corporation.Attachments = new List<Attachment>();
            if (null != logo)
            {
                corporation.Attachments.Add(logo);
            }
            BoolGenericResult<Attachment> result = this.AppService.UpdateCorporationLogo(corporation, fileUrl, newFileName);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [HttpGet]
        [ActionName(ActionConst.CERTIFICATION)]
        public ActionResult GetCorporationCertification()
        {
            IList<Attachment> certifications = this.AttachmentAppService.GetCorporationCertifications(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            ICorporationPhotosViewModel corporationCertificationsViewModel = ModelFactory.CreateModel<ICorporationPhotosViewModel>();
            corporationCertificationsViewModel.AttachmentGroup = AttachmentIdentifier.AttachmentGroup.CorporationCertification;
            corporationCertificationsViewModel.RestrictFileCount = this.AttachmentAppService.GetAttachmentGroupByID(AttachmentIdentifier.AttachmentGroup.CorporationPhoto.GetHashCode()).RestrictFileCount;
            foreach (Attachment certification in certifications)
            {
                ICorporationPhotoViewModel corporationPhotoViewModel = ModelFactory.CreateModel<ICorporationPhotoViewModel>();
                corporationPhotoViewModel.Photo = Project.Settings.ImageServer + certification.FileUrl + certification.FileName;
                corporationPhotoViewModel.PhotoID = certification.ID;
                corporationCertificationsViewModel.Photos.Add(corporationPhotoViewModel);
            }

            return View(corporationCertificationsViewModel);
        }

        [HttpPost]
        [ActionName(ActionConst.CERTIFICATION)]
        public JsonResult UpdateCorporationCertification(CorporationPhotoViewModel corporationCertification)
        {
            string temp = corporationCertification.Photo.Replace(Global.Settings.TempImageServer, "").Replace("%C3%97", "×"); ;
            string fileUrl = temp.Substring(0, temp.LastIndexOf('/') + 1);
            string fileName = temp.Substring(fileUrl.LastIndexOf('/') + 1).Replace("_360×360.jpg", "");
            FileUploadAppService.CopyFile(fileUrl, fileName);

            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            IList<Attachment> certifications = this.AttachmentAppService.GetCorporationCertifications(corporation.ID);
            corporation.Attachments = new List<Attachment>();
            if (null != certifications && certifications.Count > 0)
            {
                corporation.Attachments = certifications;
            }
            BoolGenericResult<Attachment> result = this.AppService.UpdateCorporationCertification(corporation, corporationCertification.PhotoID, fileUrl, fileName);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.PHOTO)]
        [HttpGet]
        public ActionResult GetCorporationPhotos()
        {
            IList<Attachment> photos = this.AttachmentAppService.GetCorporationPhotos(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            ICorporationPhotosViewModel corporationPhotosViewModel = ModelFactory.CreateModel<ICorporationPhotosViewModel>();
            corporationPhotosViewModel.AttachmentGroup = AttachmentIdentifier.AttachmentGroup.CorporationPhoto;
            corporationPhotosViewModel.RestrictFileCount = this.AttachmentAppService.GetAttachmentGroupByID(AttachmentIdentifier.AttachmentGroup.CorporationPhoto.GetHashCode()).RestrictFileCount;
            foreach (Attachment photo in photos)
            {
                ICorporationPhotoViewModel corporationPhotoViewModel = ModelFactory.CreateModel<ICorporationPhotoViewModel>();
                corporationPhotoViewModel.Photo = Project.Settings.ImageServer + photo.FileUrl + photo.FileName;
                corporationPhotoViewModel.PhotoID = photo.ID;
                corporationPhotosViewModel.Photos.Add(corporationPhotoViewModel);
            }

            return View(corporationPhotosViewModel);
        }

        [ActionName(ActionConst.PHOTO)]
        [HttpPost]
        public JsonResult UpdateCorporationPhoto(CorporationPhotoViewModel corporationPhoto)
        {
            string temp = corporationPhoto.Photo.Replace(Global.Settings.TempImageServer, "").Replace("%C3%97", "×"); ;
            string fileUrl = temp.Substring(0, temp.LastIndexOf('/') + 1);
            string fileName = temp.Substring(fileUrl.LastIndexOf('/') + 1).Replace("_360×360.jpg", "");
            FileUploadAppService.CopyFile(fileUrl, fileName);

            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            IList<Attachment> photos = this.AttachmentAppService.GetCorporationPhotos(corporation.ID);
            corporation.Attachments = new List<Attachment>();
            if (null != photos && photos.Count > 0)
            {
                corporation.Attachments = photos;
            }
            BoolGenericResult<Attachment> result = this.AppService.UpdateCorporationPhoto(corporation, corporationPhoto.PhotoID, fileUrl, fileName);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.REFRESH)]
        public JsonResult UpdateRefreshTime()
        {
            BoolGenericResult<CorporationStatus> result = this.AppService.UpdateCorporationRefreshTime(CorporationFactory.CreateCorporation(this.Model.MasterModel.CurrentUserModel.UserAccountID));

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [HttpGet]
        [ActionName(ActionConst.INFO)]
        public ActionResult GetCorporationInfo()
        {
            ViewBag.RawUrl = this.Request.RawUrl;
            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);

            CorporationViewModelConverter.ConvertForEdit(this.Model, corporation);

            //if (!this.Session["message"].IsNull())
            //{
            //    this.Model.Messages.Add(new Core.Message.AppMessage(this, Core.Message.MessageSeverity.Info, "message", this.Session["message"].ToString()));
            //    this.Session.Remove("message");
            //}
            return View(this.Model);
        }

        [ValidateInput(false)]
        [HttpPost]
        [ActionName(ActionConst.INFO)]
        public JsonResult UpdateCorporationInfo(CorporationViewModel corporationViewModel)
        {
            this.BindModel(corporationViewModel);
            CorporationViewModelConverter.ConvertForEdit(corporationViewModel.Item, corporationViewModel);
            BoolGenericResult<Corporation> result = this.AppService.Update(corporationViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult); 
        }

        [ActionName(ActionConst.MESSAGES)]
        public ActionResult GetUserMessages()
        {
            Corporation corporation = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            CorporationViewModelConverter.Convert(corporation, this.Model);
            return View(this.Model);
        }

        [ActionName(ActionConst.LEAVEMESSAGE)]
        public JsonResult AddMessage(UserMessageViewModel userMessageViewModel)
        {
            userMessageViewModel.Item.MessagerUser.ID = this.Model.MasterModel.CurrentUserModel.UserAccountID;
            userMessageViewModel.Item.MessagerUser.Roles.Add(RoleFactory.CreateRole(SecurityIdentifier.Role.Corporation.GetHashCode()));
            BoolGenericResult<UserMessage> result = this.UserMessageAppService.Add(userMessageViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.REPLY)]
        public JsonResult AddMessageReply(UserMessageViewModel userMessageViewModel)
        {
            userMessageViewModel.Item.MessagerUser.ID = this.Model.MasterModel.CurrentUserModel.UserAccountID;
            userMessageViewModel.Item.MessagerUser.Roles.Add(RoleFactory.CreateRole(SecurityIdentifier.Role.Corporation.GetHashCode()));
            BoolGenericResult<UserMessage> result = this.UserMessageAppService.AddUserMessageReply(userMessageViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }


        [ActionName(ActionConst.NANNIES)]
        public ActionResult GetNannies(int cp)
        {
            INanniesViewModel nanniesViewModel = ModelFactory.CreateModel<INanniesViewModel>();
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("CreateTime", true);
            NannySearch nannySearch = NannySearchFactory.CreateNannySearch(this.Model.MasterModel.CurrentUserModel.UserAccountID, orderBy, cp, Project.Settings.MaxRowsPerPage);
            long total = 0;
            IList<Nanny> nannies = this.NannyAppService.GetBySearch(nannySearch, out total).ToList();
            nannySearch.TotalRowCount = total;
            IList<INannyViewModel> nannyViewModels = NannyViewModelConverter.Convert(nannies, false);
            nanniesViewModel.Nannies = nannyViewModels;

            return View(nanniesViewModel);
        }

        [ActionName(ActionConst.SETVIP)]
        public JsonResult UpdateNannyToVip(int id, int validVIPMonth)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyVipStatus(nanny, true, validVIPMonth);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETUNVIP)]
        public JsonResult UpdateNannyToUnVip(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyVipStatus(nanny, false);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETRECOMMEND)]
        public JsonResult UpdateNannyToRecommend(int id, int recommendValidMonth)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyRecommendStatus(nanny, true, recommendValidMonth);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETUNRECOMMEND)]
        public JsonResult UpdateNannyToUnRecommend(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyRecommendStatus(nanny, false);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.DELETENANNY)]
        public JsonResult DeleteNanny(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<Nanny> result = this.NannyAppService.Delete(nanny);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETSHOW)]
        public JsonResult UpdateNannyToShow(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyOnlineStatus(nanny, true);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETUNSHOW)]
        public JsonResult UpdateNannyToUnShow(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyOnlineStatus(nanny, false);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETBID)]
        public JsonResult UpdateNannyToBid(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyBidStatus(nanny, true);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.SETUNBID)]
        public JsonResult UpdateNannyToUnBid(int id)
        {
            Nanny nanny = NannyFactory.CreateNanny(id);
            BoolGenericResult<NannyStatus> result = this.NannyAppService.UpdateNannyBidStatus(nanny, false);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.NEWS)]
        public ActionResult GetNews(int cp)
        {
            Dictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("CreateTime", true);
            CorporationNewSearch searchParams = CorporationNewSearchFactory.CreateCorporationNewSearch(this.Model.MasterModel.CurrentUserModel.UserAccountID,
                orderBy, cp, Project.Settings.MaxRowsPerPage);
            long total = 0;
            IList<CorporationNew> corporationNews = this.CorporationNewAppService.GetBySearch(searchParams, out total).ToList();

            ICorporationNewViewModel corporationNewViewModel = ModelFactory.CreateModel<ICorporationNewViewModel>();
            corporationNewViewModel.News = corporationNews;

            return View(corporationNewViewModel);
        }

        [HttpGet]
        [ActionName(ActionConst.EDITNEW)]
        public ActionResult AddNew(int? id)
        {
            CorporationNew corporationNew = new CorporationNew();
            if (id.HasValue)
            {
                corporationNew = this.CorporationNewAppService.GetById(id.Value);
            }

            return View(corporationNew);
        }

        [HttpPost]
        [ActionName(ActionConst.EDITNEW)]
        public JsonResult UpdateNew(CorporationNewViewModel corporationNew)
        {
            BoolGenericResult<CorporationNew> result = null;
            if (corporationNew.Item.ID > 0)
            {
                result = this.CorporationNewAppService.Update(corporationNew.Item);
            }
            else
            {
                result = this.CorporationNewAppService.Add(corporationNew.Item);
            }

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.BIDCONSIGN)]
        [ChildActionOnly]
        public JsonResult AddConsignBidder(int id, int nannyId)
        {
            Consign consign = ConsignFactory.CreateConsign(id);
            Nanny nanny = NannyFactory.CreateNanny(nannyId);
            BoolGenericResult<ConsignBidder> result = this.ConsignAppService.AddConsignBidder(consign, nanny);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName(ActionConst.BIDDINGCONSIGN)]
        public ActionResult GetBiddingConsigns()
        {
            ICorporationBiddingConsignViewModel corporationBiddingConsignViewModel = ModelFactory.CreateModel<ICorporationBiddingConsignViewModel>();
            IList<ConsignBidder> consignBidders = this.ConsignAppService.GetConsignsByCorporation(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            corporationBiddingConsignViewModel.ConsignBidders = ConsignBidderViewModelConverter.Convert(consignBidders);

            return View(corporationBiddingConsignViewModel);
        }

        [ActionName(ActionConst.NANNY)]
        [HttpGet]
        public ActionResult AddNanny()
        {
            INannyViewModel nannyViewModel = ModelFactory.CreateModel<INannyViewModel>();
            Nanny nanny = NannyFactory.CreateNanny(0);
            nannyViewModel.Item = nanny;
            NannyViewModelConverter.ConvertForEdit(nannyViewModel, nanny);

            return View(nannyViewModel);
        }

        [ActionName(ActionConst.NANNY)]
        [HttpPost]
        public JsonResult AddNanny(NannyViewModel nannyViewModel)
        {
            nannyViewModel.Item.Corporation = CorporationFactory.CreateCorporation(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            NannyViewModelConverter.ConvertForEdit(nannyViewModel.Item, nannyViewModel);
            BoolGenericResult<Nanny> result = this.NannyAppService.AddNannyByCorporation(nannyViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        private void SaveCorporationUnReadNote(long unReadNote)
        {
            if (!CookieHelper.IsExsit(Project.Settings.MulalaHistoryCookieName))
            {
                CookieHelper.CreateCookie(Project.Settings.MulalaHistoryCookieName);
            }

            CookieHelper.SetCookie(MulalaAppConst.CORPORATIONUNREADNOTE, unReadNote.ToString(), Project.Settings.MulalaHistoryCookieName);
        }
    }
}
